<?php

require_once('functions.php');
$member_id	= $session->get("member_id");

// Update top players.
$template->assign("players",get_top_players());

// Member is registered.
if($member_id)
{
	redirect("index.php");
}

// Assign title page.
$template->assign("title", _LB_GET_PASSWORD);

// Get data from request form.
$data = $_REQUEST;
$message_error = array();
if(isset($data['form_id']))
{
	$sess_form_id = $session->get('form_id');
	if($sess_form_id && $sess_form_id != $data['form_id'])
	{
		redirect("index.php");
	}
	$session->set('form_id', "");
	// Check blank fields
	if(	empty($data['email']))
	{
		$message_error[] = _MSG_FILL_REQUIRED_INFO;
	}
	
	// Check valid email
	if(!validEmail($data['email']))
	{
		$message_error[] = _ERR_INVALID_EMAIL;
	}
	
	// All data are valid.
	if(count($message_error) == 0)
	{
		$email = $data['email'];
		$newpassword = generatePassword();
		$database->set_query("SELECT * FROM member WHERE email = '$email' LIMIT 1");
		$member = $database->get_object();
		if($member)
		{
			$name = !empty($member->fullname) ? $member->fullname : $member->username ;
			if($database->query("UPDATE member SET password = MD5('$newpassword') WHERE id = " . $member->id))
			{
				$to			= $email;
				$subject	= _LB_REQUEST_NEW_PASSWORD;
				$body		= _LB_HI.", {$name}\n\n"._LB_YOUR_NEW_INFORAMTION.": \n "._LB_USERNAME.": {$member->username}\n "._LB_PASSWORD.": {$newpassword}\n\n"._LB_THANKS.",\n"._LB_SUPPORT_TEAM.".";
				if (mail_utf8($to, $subject, $body)) {
					$message_error[] = "<p style='color: green;'>"._MSG_EMAIL_SENT."</p>";
				} else {
					$message_error[] = "<p>Sending failed. Please try later.</p>";
				}
			}
			else
			{
				$message_error[] = "Creating new password failed. Please try later.";
			}
		}
		else
		{
			$message_error[] = _ERR_EMAIL_NOT_EXIST;
		}
	}
	else
	{
		$form_id = uniqid();		
		$session->set('form_id', $form_id);
		$template->assign("form_id", $form_id);
		$template->assign("email", $data['email']);
	}
}
else
{
	$form_id = uniqid();
	$template->assign("form_id", $form_id);
	$session->set('form_id', $form_id);
}
$template->assign("email", $data['email'] ? $data['email'] : "");
$template->assign("message", implode("<br>", $message_error));
$template->display("forgotpassword.tpl");
?>
